<?php
//error_reporting(E_ALL);

class ShareInfoModule {

    private static $_denywords = array('火锅阁', '小肥羊');

    public function getcate() {
        global $_FANWE;

        $pid = intval($_GET['pid']);
        $type = intval($_GET['type']);
        $anli = $_GET['anli'] == 1 ? 1 : 0;
        $where = 'status=1 AND cate_type='.$type.($type==0 ? ' AND anli='.$anli : '').' AND parent_id='.$pid.' AND canpub=1';
        if($anli || $type == 3) {
            $sql = 'SELECT * FROM '.FDB::table('wogu_realname_shop').' WHERE uid='.$_FANWE['uid'];
            $r = FDB::fetchFirst($sql);
            $stype = $r['stype'];
            $auth_type = $r['auth_type']+1;
            $key = 'auth_type' . ($stype == 0 ? '' : '2');
            $where .= " AND substr({$key},{$auth_type},1)=1";
        } else {
            $where .= ' AND p_cansub=1';
        }
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE '.$where.' ORDER BY sort ASC,cate_id ASC';
        $cate_list = FDB::fetchAll($sql);
        $cate_list = toFormatTree($cate_list,array('cate_name'),'cate_id');
        echo '<select name="cate_id">';
        foreach ($cate_list as $key => $v) {
            echo '<option value="'.$v['cate_id'].'">'.$v['cate_name'].'</option>';
        }
        echo '</select>';
    }

    public function delart() {
        global $_FANWE;

        $id = intval($_GET['id']);
        $sql = 'UPDATE '.FDB::table('article').' SET flag=1 WHERE id='.$id;
        FDB::query($sql);
        showSuccess('提示', '文章删除成功！', FU('shareinfo/listart'));
    }

    public function listart() {
        global $_FANWE;

        if($_GET['op'] == 'setdefault') {
            $id = intval($_GET['id']);
            $sql = 'UPDATE '.FDB::table('article').' SET isdefault=0 WHERE uid='.$_FANWE['uid'];
            FDB::query($sql);
            $sql = 'UPDATE '.FDB::table('article').' SET isdefault=1 WHERE id='.$id;
            FDB::query($sql);
            showSuccess('提示', '设置成功！', $_SERVER['HTTP_REFERER']);
        }

        $anli = $_GET['anli'] || $_GET['jiage'] ? 1 : 0;
        $jiage = $_GET['jiage'] ? 1 : 0;
        $where = 'uid='.$_FANWE['user']['uid'].' AND flag=0 AND anli='.$anli.' AND jiage='.$jiage;
        $sql = 'SELECT COUNT(id) FROM '.FDB::table('article').' WHERE '.$where;
        $count = FDB::resultFirst($sql);
        $page_args = array('anli' => $anli);
        $pager = buildPage('shareinfo/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);

        $sql = 'SELECT * FROM '.FDB::table('article').' WHERE '.$where.' ORDER BY id DESC LIMIT '.$pager['limit'];
        $article_list = FDB::fetchAll($sql);

        // 实名认证信息
        $sql = 'SELECT * FROM '.FDB::table('wogu_realname_shop').' WHERE uid='.$_FANWE['uid'];
        $realname = FDB::fetchFirst($sql);
        if($realname['stype'] == 1) {
            $sql = 'SELECT * FROM '.FDB::table('article').' WHERE uid='.$_FANWE['uid'].' AND anli=1 AND isdefault=1';
            $anliinfo = FDB::fetchFirst($sql);
        }

        include template('page/shareinfo/shareinfo_listart');
        display();
    }

    public function checkword($word) {
    	foreach(self::$_denywords as $v) {
    	    if(strpos($word, $v) !== false)
    	        return $v;
    	}

    	return true;
    }

    public function shareart() {
        global $_FANWE;

        if($_FANWE['user']['user_type'] == 1 && $_FANWE['user']['realname_shop'] == 0)
            showError('错误信息', '请先实名认证！', FU('settings/realname'));

        if(!$_GET['jiage']) {
            $anli = $_GET['anli'] == 1 ? 1 : 0;
            $where = ' status=1 AND cate_type=0 AND anli='.$anli.' AND parent_id!=0 AND canpub=1';
            if($anli) {
                $sql = 'SELECT * FROM '.FDB::table('wogu_realname_shop').' WHERE uid='.$_FANWE['uid'];
                $r = FDB::fetchFirst($sql);
                $stype = $r['stype'];
                $auth_type = $r['auth_type']+1;
                $key = 'auth_type' . ($stype == 0 ? '' : '2');
                $where .= " AND substr({$key},{$auth_type},1)=1";
            }
            $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE '.$where.' ORDER BY sort ASC,cate_id ASC';
            $cate_list = FDB::fetchAll($sql);
            if(!empty($cate_list)) {
                $pids = array();
                foreach($cate_list as $v) {
                    $pids[] = $v['parent_id'];
                }
                $pids = array_unique($pids);
                $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id IN('.implode(',', $pids).') ORDER BY sort ASC,cate_id ASC';
                $cate_list = FDB::fetchAll($sql);
                $cate_list = toFormatTree($cate_list,array('cate_name'),'cate_id');
            }
        }

        $id = intval($_GET['id']);
        if($id) {
            $sql = 'SELECT * FROM '.FDB::table('article').' WHERE id='.$id . ' AND uid='.$_FANWE['user']['uid'];
            $article = FDB::fetchFirst($sql);
            if(!$article) {
                showError('错误信息', '文章不存在！', FU('shareinfo/shareinfo'));
            }

            if(!$_GET['jiage']) {
                $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id='.$article['cate_id'];
                $r = FDB::fetchFirst($sql);
                $cate_name = $r['cate_name'];
                $anli = $article['anli'];
            }

            $article['bsj'] = !$article['bsj'] ? '' : date('Y-m-d', $article['bsj']);
            $article['esj'] = !$article['esj'] ? '' : date('Y-m-d', $article['esj']);
        }

        $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE uid='.$_FANWE['uid'];
        $shopinfo = FDB::fetchFirst($sql);
        include template('page/shareinfo/shareinfo_shareart');
        display();
    }

    protected function _ajaxMsg($status, $data = '') {
        if(isset($_GET['ajax'])) {
            ajaxmsg2($status, $data);
        } else {
            exit($data);
        }
    }

    public function saveart() {
        global $_FANWE;
        if($_FANWE['user']['user_type'] == 0) {
            $this->_ajaxMsg(1,'个人用户不能发布案例/经验');
        }

        $jiage = $_POST['jiage'] == 1 ? 1 : 0;
        if(!$jiage) {
            $uid = $_FANWE['uid'] == 1 && is_numeric($_POST['uid']) ? $_POST['uid'] : $_FANWE['uid'];
            $anli = $_POST['anli'] == 1 ? 1 : 0;
            $tip = $anli == 1 ? '案例' : '经验';
            $id = intval($_POST['id']);
            if($id) {
                $sql = 'SELECT * FROM '.FDB::table('article').' WHERE id='.$id . ' AND uid='.$uid;
                $article = FDB::fetchFirst($sql);
                if(!$article) {
                    $this->_ajaxMsg(1,$tip.'不存在！');
                }
            }

            // 要限制分享次数只需去掉注释
            if(!$id) {
                $lastsharetime = strtotime($_FANWE['user']['last_shareart']);
                $nowtime = strtotime(date('Y-m-d'));
                if($nowtime == $lastsharetime) {
                    $this->_ajaxMsg(1,"一天只能分享一篇{$tip}！");
                }
            }

            $title = htmlspecialchars(trim($_POST['title']));
            if(true !== ($denyword = self::checkword($title)))
                $this->_ajaxMsg(1,"标题中含有敏感词“{$denyword}”");
            $content = trim($_POST['content']);
            $content = preg_replace(array('/\'/', '/<script[\s\S]+?\/script>/i'), array('&#039;',''), $content);
            if(true !== ($denyword = self::checkword($content)))
                $this->_ajaxMsg(1,"内容中含有敏感词“{$denyword}”");
            if(empty($title) || empty($content)) {
                $this->_ajaxMsg(1,'标题或内容为空！');
            }


            if(!$id || (!empty($_FILES['img']) && $_FILES['img']['error']==0)) {
                if((empty($_FILES['img']) || $_FILES['img']['error']!=0) && $uid == 1) {
                    $savepath = '/public/v1/img/default.jpg';
                    $sizeinfo = array(257, 257);
                } else {
                    if(empty($_FILES['img']) || $_FILES['img']['size'] <= 0 || $_FILES['img']['error'] != 0) {
                        $this->_ajaxMsg(1,'图片上传失败！');
                    }

                    $sizeinfo = getimagesize($_FILES['img']['tmp_name']);
                    $width = $sizeinfo[0];
                    $height = $sizeinfo[1];
                    if(!$sizeinfo || $width < 257 || $width > 600 || $height < 257 || $height > 600) {
                        $this->_ajaxMsg(1,'图片尺寸不符合规定！');
                    }

                    $dir = FANWE_ROOT . 'public/upload2/';
                    $dir1 = date('Ym') . '/' . date('d') . '/';
                    $dir2 = $dir . $dir1;
                    if(!is_dir($dir2)) {
                        mkdir($dir2, 0777, true);
                    }
                    $filename = date('His').strtolower(random2(16)) . '.jpg';
                    $path = $dir2 . $filename;
                    $savepath = '/public/upload2/' . $dir1 . $filename;
                    if(!move_uploaded_file($_FILES['img']['tmp_name'], $path)) {
                        $this->_ajaxMsg(1,'图片上传失败！');
                    }

                	$water_mark = FANWE_ROOT . $_FANWE['setting']['water_image']; //配置于config
                	$alpha = $_FANWE['setting']['water_alpha'];
                	$place = $_FANWE['setting']['water_position'];
                	$addwater = $_FANWE['setting']['water_mark'];
                	if($addwater) {
                	    include_once fimport('class/image');
                        $image = new Image();
                	    $image->water($path, $water_mark, $alpha, $place);
                	}

                    if($id) {
                        @unlink('.'.$article['img']);
                    }
                }
            }

            $cate_id = $article  ? $article['cate_id'] : intval($_POST['cate_id']);
            if(!$cate_id) $this->_ajaxMsg(1,'请选择分类！');
            $desc = $title;
            $shop_name = '';
            $province = 0;
            $city = 0;
            $price = 0;
            $price2 = 0;
            $bsj = 0;
            $esj = 0;
            $red_money = 0;
            if($anli == 1) {
                $shop_name = htmlspecialchars(trim($_POST['shop_name']));
                $province = intval($_POST['province']);
                $city = intval($_POST['city']);
                $price = floatval($_POST['price']);
                if(!$price) $this->_ajaxMsg(1,'请填写价格！');
                $price2 = floatval($_POST['price2']);
                $total_fee = $price2 > 0 ? $price2 : $price;
                $red_money = floatval($_POST['red_money']);
                if(0 != $red_money%100) $this->_ajaxMsg(1,'红包金额必须是100的整数倍');
                if($red_money > $total_fee) $this->_ajaxMsg(1,'红包金额不能大于销售价');
                $provincename = htmlspecialchars(trim($_POST['provincename']));
                $cityname = htmlspecialchars(trim($_POST['cityname']));
                $desc = '店铺区域:'.$provincename.$cityname.',店铺名称:'.$shop_name.',价格:'.$price.',标题:'.$title;
                $bsj = empty($_POST['bsj']) ? 0 : strtotime($_POST['bsj']);
                $esj = empty($_POST['esj']) ? 0 : strtotime($_POST['esj']);
            }

            if($id) {
                $sql = "UPDATE ".FDB::table('article')." SET title='{$title}',content='{$content}',cate_id='{$cate_id}',seo_desc='{$desc}',seo_keywords='{$title}',shop_name='{$shop_name}',province='{$province}',city='{$city}',price='{$price}',price2='{$price2}',anli='{$anli}',bsj={$bsj},esj={$esj},red_money={$red_money}";
                if($savepath) {
                    $sql .= ",img='{$savepath}',width='{$sizeinfo[0]}',height='{$sizeinfo[1]}'";
                }
                $sql .= ' WHERE id='.$id;
                FDB::query($sql);
            } else {
                $sql = "INSERT INTO ".FDB::table('article')." (title,content,cate_id,".($savepath ? "img,width,height," : "")."sort,uid,create_time,status,seo_desc,seo_keywords,shop_name,province,city,price,price2,anli,bsj,esj,red_money) VALUES('{$title}', '{$content}', '{$cate_id}', ".($savepath ? "'{$savepath}', '{$sizeinfo[0]}', '{$sizeinfo[1]}'," : "")." '100','{$uid}','".time()."',1,'{$desc}','{$title}','{$shop_name}','{$province}','{$city}','{$price}','{$price2}','{$anli}',{$bsj},{$esj},{$red_money})";
                if(FDB::query($sql)) {
                    $artid = FDB::insertId();
                    FDB::query("UPDATE ".FDB::table('user')." SET last_shareart='".date('Y-m-d')."',jy_num=jy_num+1 WHERE uid ={$uid}", 'UNBUFFERED');

                    $data = array(
                        'content' => '我分享了'.$tip.'《<a href="/article.php?action=show&id='.$artid.'">'.$title.'</a>》<p><img src="'.$savepath.'" width="257"/></p>',
                        'albumid' => 0,
                        'mytype' => 'article',
                        'articleid' => $artid
                    );
                    $share = FS('Share')->submit($data,true,true, $uid);
                }
            }

            $this->_ajaxMsg(0,$tip.'提交成功！');
        } else {
            $id = intval($_POST['id']);
            if($id) {
                $sql = 'SELECT * FROM '.FDB::table('article').' WHERE id='.$id . ' AND uid='.$_FANWE['uid'];
                $article = FDB::fetchFirst($sql);
                if(!$article) {
                    $this->_ajaxMsg(1,'价格不存在！');
                }
            }

            $price = floatval($_POST['price']);
            if(!$price) $this->_ajaxMsg(1,'请填写价格！');
            $content = trim($_POST['content']);
            $content = preg_replace(array('/\'/', '/<script[\s\S]+?\/script>/i'), array('&#039;',''), $content);
            if(empty($content)) {
                $this->_ajaxMsg(1,'内容为空！');
            }
            if(true !== ($denyword = self::checkword($content)))
                $this->_ajaxMsg(1,"内容中含有敏感词“{$denyword}”");

            if($id) {
                $sql = "UPDATE ".FDB::table('article')." SET content='{$content}',price='{$price}' WHERE id=".$id;
                FDB::query($sql);
            } else {
                $sql = "INSERT INTO ".FDB::table('article')." (uid,content,price,anli,jiage) VALUES('{$_FANWE['uid']}','{$content}','{$price}','1','1')";
                FDB::query($sql);
            }

            $this->_ajaxMsg(0,'价格提交成功！');
        }
    }

    public function pubinfo() {
        global $_FANWE;
        if($_FANWE['user']['user_type'] == 1 && $_FANWE['user']['realname_shop'] == 0)
            showError('错误信息', '请先实名认证！', FU('settings/realname'));

        $where = 'status=1 AND cate_type=3 AND parent_id!=0 AND canpub=1';
        $sql = 'SELECT * FROM '.FDB::table('wogu_realname_shop').' WHERE uid='.$_FANWE['uid'];
        $r = FDB::fetchFirst($sql);
        $stype = $r['stype'];
        $auth_type = $r['auth_type']+1;
        $key = 'auth_type' . ($stype == 0 ? '' : '2');
        $where .= " AND substr({$key},{$auth_type},1)=1";

        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE '.$where.' ORDER BY sort ASC,cate_id ASC';
        $cate_list = FDB::fetchAll($sql);
        $pids = array();
        foreach($cate_list as $v) {
            $pids[] = $v['parent_id'];
        }
        $pids = array_unique($pids);
        $cate_list = null;
        if(!empty($pids)) {
            $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id IN('.implode(',', $pids).') ORDER BY sort ASC,cate_id ASC';
            $cate_list = FDB::fetchAll($sql);
            $cate_list = toFormatTree($cate_list,array('cate_name'),'cate_id');
        }

        $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE uid='.$_FANWE['user']['uid'];
        $shopinfo = FDB::fetchFirst($sql);
        if(!empty($shopinfo['cate_id'])) {
            $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id='.$shopinfo['cate_id'];
            $r = FDB::fetchFirst($sql);
            $cate_name = $r['cate_name'];
        }
        $cities = include './public/city.php';
        $shopinfo['province_show'] = $cities['all'][$shopinfo['province']]['name'];
        $shopinfo['city_show'] = $cities['all'][$shopinfo['city']]['name'];

        include template('page/shareinfo/shareinfo_pubinfo');
        display();
    }

    public function saveinfo() {
        global $_FANWE;

        $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE uid='.$_FANWE['user']['uid'];
        $shopinfo = FDB::fetchFirst($sql);

        $content = trim($_POST['content']);
        $content = preg_replace(array('/\'/', '/<script[\s\S]+?\/script>/i'), array('&#039;',''), $content);
        if(true !== ($denyword = self::checkword($content)))
            exit("商家描述中含有敏感词“{$denyword}”");
        $address = htmlspecialchars(trim($_POST['address']));
        if(empty($content) || empty($address)) {
            exit('地址或内容为空！');
        }

        $telphone = str_replace(array(',', '.'), '', trim($_POST['telphone']));
        $telphone = isTel($telphone) ? $telphone : '';
        $telphone2 = str_replace(array(',', '.'), '', trim($_POST['telphone2']));
        $telphone2 = isTel($telphone2) ? $telphone2 : '';
        $mobile = str_replace(array(',', '.'), '', trim($_POST['mobile']));
        $mobile = !empty($mobile) && is_numeric($mobile) ? $mobile : '';
        $mobile2 = str_replace(array(',', '.'), '', trim($_POST['mobile2']));
        $mobile2 = !empty($mobile2) && is_numeric($mobile2) ? $mobile2 : '';

        if(!empty($telphone2) && empty($telphone))
            exit('请先填写电话号码1');

        if(!empty($mobile2) && empty($mobile))
            exit('请先填写手机号码1');

        if(!$telphone && !$telphone2 && !$mobile && !$mobile2) {
            exit('请至少填写一个电话号码或手机号码！');
        }

        if($telphone != '' && $telphone == $telphone2)
            exit('电话号码重复！');

        if($mobile != '' && $mobile == $mobile2)
            exit('手机号码重复！');

        $cate_id = intval($_POST['cate_id']);
        if(!$cate_id && $shopinfo['cate_id'] == 0) exit('请选择分类！');
        $cate_id = $cate_id ? $cate_id : $shopinfo['cate_id'];
        $catname = $_FANWE['cache']['goods_category']['all'][$cate_id]['cate_name'];
        $desc = '商家名称：'.$shopinfo['name'].(!empty($telphone) ? ',电话号码：'.$telphone : '').(!empty($mobile) ? ',手机号码：'.$mobile : '').',地址：'.$address.',分类：'.$catname.',';

        if(empty($shopinfo['img']) || (!empty($_FILES['img']) && $_FILES['img']['error']==0)) {
            if(empty($_FILES['img']) || $_FILES['img']['size'] <= 0 || $_FILES['img']['error'] != 0) {
                exit('图片上传失败！');
            }

            $sizeinfo = getimagesize($_FILES['img']['tmp_name']);
            $width = $sizeinfo[0];
            $height = $sizeinfo[1];
            if(!$sizeinfo || $width < 257 || $width > 600 || $height < 257 || $height > 600) {
                exit('图片尺寸不符合规定！');
            }

            $dir = FANWE_ROOT . 'public/upload2/';
            $dir1 = date('Ym') . '/' . date('d') . '/';
            $dir2 = $dir . $dir1;
            if(!is_dir($dir2)) {
                mkdir($dir2, 0777, true);
            }
            $filename = date('His').strtolower(random2(16)) . '.jpg';
            $path = $dir2 . $filename;
            $savepath = '/public/upload2/' . $dir1 . $filename;
            if(!move_uploaded_file($_FILES['img']['tmp_name'], $path)) {
                exit('图片上传失败！');
            }

        	$water_mark = FANWE_ROOT . $_FANWE['setting']['water_image']; //配置于config
        	$alpha = $_FANWE['setting']['water_alpha'];
        	$place = $_FANWE['setting']['water_position'];
        	$addwater = $_FANWE['setting']['water_mark'];
        	if($addwater) {
        	    include_once fimport('class/image');
                $image = new Image();
        	    $image->water($path, $water_mark, $alpha, $place);
        	}

            if(!empty($shopinfo['img'])) {
                @unlink('.'.$shopinfo['img']);
            }
        }

        //提取关键词
        $keywords = array('火锅公司' => true, '火锅店' => true, '火锅大师' => false, '火锅大厨' => false,);
        foreach($keywords as $find => $b) {
            $keyword = strstr($shopinfo['name'], $find, $b);
            if(false !== $keyword) {
                if(!$b)
                    $keyword = str_replace($find, '', $keyword);
                break;
            }
        }

        $sql = "UPDATE ".FDB::table('wogu_user_shop')." SET content='{$content}',create_time='".time()."',seo_desc='{$desc}',robot_keyword='{$keyword}',mobile='{$mobile}',mobile2='{$mobile2}',telphone='{$telphone}',telphone2='{$telphone2}',address='{$address}',cate_id='{$cate_id}'";
        if($savepath) {
            $sql .= ",img='{$savepath}',width='{$sizeinfo[0]}',height='{$sizeinfo[1]}'";
        }
        $sql .= ' WHERE uid='.$_FANWE['user']['uid'];
        FDB::query($sql);
        if($shopinfo['cate_id'] == 0) {
            $data = array(
                'content' => '我分享了商家资料《<a href="/shopinfo.php?action=show&id='.$shopinfo['id'].'">'.$shopinfo['name'].'</a>》<p><img src="'.$savepath.'" width="257"/></p>',
                'albumid' => 0,
                'mytype' => 'shopinfo',
                'id' => $_FANWE['uid']
            );
            $share = FS('Share')->submit($data,true,true);
        }

        exit('资料提交成功！');
    }

    public function pubinfo2() {
        global $_FANWE;

        $id = intval($_GET['id']);

        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE status=1 AND cate_type=3 AND parent_id!=0 AND canpub=1 ORDER BY sort ASC,cate_id ASC';
        $cate_list = FDB::fetchAll($sql);
        $pids = array();
        foreach($cate_list as $v) {
            $pids[] = $v['parent_id'];
        }
        $pids = array_unique($pids);

        $cate_list = array();
        if(!empty($pids)) {
            $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id IN('.implode(',', $pids).') ORDER BY sort ASC,cate_id ASC';
            $cate_list = FDB::fetchAll($sql);
            $cate_list = toFormatTree($cate_list,array('cate_name'),'cate_id');
        }

        if($id) {
            $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE id='.$id;
            $shopinfo = FDB::fetchFirst($sql);
            $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id='.$shopinfo['cate_id'];
            $r = FDB::fetchFirst($sql);
            $cate_name = $r['cate_name'];
        }

        include template('page/shareinfo/shareinfo_pubinfo_admin');
        display();
    }

    public function saveinfo2() {
        global $_FANWE;

        $uid =  intval($_POST['uid']);
        $id = intval($_POST['id']);
        if($id>0) {
            $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE id='.$id;
            $shopinfo = FDB::fetchFirst($sql);
        }

        $name = htmlspecialchars(trim($_POST['name']));
        $content = trim($_POST['content']);
        $content = preg_replace(array('/\'/', '/<script[\s\S]+?\/script>/i'), array('&#039;',''), $content);
        $address = htmlspecialchars(trim($_POST['address']));
        if(empty($name) || empty($address)) {
            exit('商家名称、地址或内容为空！');
        }

        if(empty($content)) {
            $content = '<p><img src="/public/v1/img/default.jpg"/></p>';
        }

        $telphone = trim($_POST['telphone']);
        $telphone = isTel($telphone) ? $telphone : '';
        $telphone2 = trim($_POST['telphone2']);
        $telphone2 = isTel($telphone2) ? $telphone2 : '';
        $mobile = trim($_POST['mobile']);
        $mobile = !empty($mobile) && is_numeric($mobile) ? $mobile : '';
        $mobile2 = trim($_POST['mobile2']);
        $mobile2 = !empty($mobile2) && is_numeric($mobile2) ? $mobile2 : '';
        $show_v2 = intval($_POST['show_v2']);
        $lat = htmlspecialchars($_POST['lat']);
        $lng = htmlspecialchars($_POST['lng']);

        if(!$telphone && !$telphone2 && !$mobile && !$mobile2) {
            exit('请至少填写一个电话号码或手机号码！');
        }

        if($telphone != '' && $telphone == $telphone2)
            exit('电话号码重复！');

        if($mobile != '' && $mobile == $mobile2)
            exit('手机号码重复！');

        $cate_id = intval($_POST['cate_id']);
        if(!$cate_id && (!$id || $shopinfo['cate_id']==0)) exit('请选择分类！');
        $cate_id = !$id ? $cate_id : (!$shopinfo['cate_id'] ? $cate_id : $shopinfo['cate_id']);
        $catname = $_FANWE['cache']['goods_category']['all'][$cate_id]['cate_name'];
        $desc = '商家名称：'.$name.(!empty($telphone) ? ',电话号码：'.$telphone : '').(!empty($mobile) ? ',手机号码：'.$mobile : '').',地址：'.$address.',分类：'.$catname.',';

        $orderby = 0;
        if(!$id || (!empty($_FILES['img']) && $_FILES['img']['error']==0)) {
            if(empty($_FILES['img']) || $_FILES['img']['error']!=0) {
                $savepath = '/public/v1/img/default.jpg';
                $sizeinfo = array(257, 257);
                $orderby = 1;
            } else {
                if(empty($_FILES['img']) || $_FILES['img']['size'] <= 0 || $_FILES['img']['error'] != 0) {
                    exit('图片上传失败！');
                }

                $sizeinfo = getimagesize($_FILES['img']['tmp_name']);
                $width = $sizeinfo[0];
                $height = $sizeinfo[1];
                if(!$sizeinfo || $width < 257 || $width > 600 || $height < 257 || $height > 600) {
                    exit('图片尺寸不符合规定！');
                }

                $dir = FANWE_ROOT . 'public/upload2/';
                $dir1 = date('Ym') . '/' . date('d') . '/';
                $dir2 = $dir . $dir1;
                if(!is_dir($dir2)) {
                    mkdir($dir2, 0777, true);
                }
                $filename = date('His').strtolower(random2(16)) . '.jpg';
                $path = $dir2 . $filename;
                $savepath = '/public/upload2/' . $dir1 . $filename;
                if(!move_uploaded_file($_FILES['img']['tmp_name'], $path)) {
                    exit('图片上传失败！');
                }

            	$water_mark = FANWE_ROOT . $_FANWE['setting']['water_image']; //配置于config
            	$alpha = $_FANWE['setting']['water_alpha'];
            	$place = $_FANWE['setting']['water_position'];
            	$addwater = $_FANWE['setting']['water_mark'];
            	if($addwater) {
            	    include_once fimport('class/image');
                    $image = new Image();
            	    $image->water($path, $water_mark, $alpha, $place);
            	}

                if($id>0) {
                    @unlink('.'.$shopinfo['img']);
                }
            }
        }

        $province = intval($_POST['province']);
        $city = intval($_POST['city']);
        //提取关键词
        $keywords = array('火锅公司' => true, '火锅店' => true, '火锅大师' => false, '火锅大厨' => false,);
        foreach($keywords as $find => $b) {
            $keyword = strstr($name, $find, $b);
            if(false !== $keyword) {
                if(!$b)
                    $keyword = str_replace($find, '', $keyword);
                break;
            }
        }

        $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop')." WHERE name='$name' AND province='$province' AND city='$city'".($id>0 ? " AND id!=$id" : '');
        $r = FDB::fetchFirst($sql);
        if(!empty($r)) {
            exit('已经有同名的火锅公司存在！');
        }

        if($id>0) {
            $sql = "UPDATE ".FDB::table('wogu_user_shop')." SET name='{$name}',content='{$content}',cate_id='{$cate_id}',uid='{$uid}',province='{$province}',city='{$city}',create_time='".time()."',seo_desc='{$desc}',robot_keyword='{$keyword}',mobile='{$mobile}',mobile2='{$mobile2}',telphone='{$telphone}',telphone2='{$telphone2}',address='{$address}',orderby='{$orderby}',show_v2='{$show_v2}',lat='{$lat}',lng='{$lng}'";
            if($savepath) {
                $sql .= ",img='{$savepath}',width='{$sizeinfo[0]}',height='{$sizeinfo[1]}'";
            }
            $sql .= ' WHERE id='.$id;
            FDB::query($sql);
        } else {
            $sql = "INSERT INTO ".FDB::table('wogu_user_shop')." (name,content,cate_id,img,width,height,uid,province,city,create_time,seo_desc,robot_keyword,mobile,mobile2,telphone,telphone2,address,orderby,show_v2,lat,lng) VALUES('{$name}', '{$content}', '{$cate_id}', '{$savepath}', '{$sizeinfo[0]}', '{$sizeinfo[1]}','{$uid}','{$province}','{$city}','".time()."','{$desc}','{$keyword}','{$mobile}','{$mobile2}','{$telphone}','{$telphone2}','{$address}','{$orderby}', '{$show_v2}','{$lat}','{$lng}')";
            if(FDB::query($sql)) {}
        }

        exit('资料提交成功！');
    }

    public function order() {
        global $_FANWE;

        if($_GET['op'] == 'del') {
            $id = intval($_GET['id']);
            $sql = 'UPDATE '.FDB::table('wogu_order').' SET isdel=1 WHERE id='.$id;
            FDB::query($sql);

            if(isset($_GET['ajax'])) {
                exit(json_encode(array('status' => 1)));
            } else {
                showSuccess('提示', '删除成功！', FU('shareinfo/order'));
            }
        } else {
            $where = 'isdel=0 AND userid='.$_FANWE['uid'];
            $sql = 'SELECT COUNT(id) FROM '.FDB::table('wogu_order').' WHERE '.$where;
            $count = FDB::resultFirst($sql);
            $page_args = array();
            $pager = buildPage('shareinfo/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);
            $order_list = array();
            if($_FANWE['page'] <= $pager['page']) {
                $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE '.$where.' ORDER BY id DESC LIMIT '.$pager['limit'];
                $order_list = FDB::fetchAll($sql);
                if(!empty($order_list)) {
                    foreach($order_list as $v) {
                        $uids[] = $v['shopid'];
                        $orderids[] = $v['id'];
                    }
                    $uids = array_unique($uids);
                    $sql = 'SELECT uid,user_name FROM '.FDB::table('user').' WHERE uid IN('.implode(',', $uids).')';
                    $tmparr = FDB::fetchAll($sql);
                    $users = array();
                    foreach($tmparr as $v)
                        $users[$v['uid']] = $v['user_name'];

                    $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE orderid IN('.implode(',', $orderids).')';
                    $res = FDB::query($sql);
                    while($r = FDB::fetch($res)) {
                        $pis[$r['orderid']] = $r;
                    }
                }
            }

            if(isset($_GET['ajax'])) {
                $statuses = array('待上传合同确认', '商家已上传合同', '合同已签', '已付预付款', '婚礼全款已支付完成');
                foreach ($order_list as &$v) {
                    $v['status'] = $statuses[$v['flag']];
                    $v['service_status'] = (time() > (strtotime($v['service_day']) + 3600 * 24)) ? '服务完成' : '婚礼服务进行中';
                    $v['sj'] = date('Y-m-d', $v['dateline']);
                    $v['shopname'] = $users[$v['shopid']];
                }

                exit(json_encode(array(
                    'list' => $order_list
                )));
            } else {
                include template('page/shareinfo/shareinfo_order');
                display();
            }
        }
    }

    public function doorder() {
        exit;
        global $_FANWE;

        $orderid = intval($_GET['id']);
        $orderinfo = FDB::fetchFirst('SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$orderid);
        if(!$orderinfo) {
            showError('错误信息', '订单不存在！', FU('shareinfo/order'));
        }

        if($orderinfo['flag'] != 1)
            showError('错误信息', '订单已失效！', FU('shareinfo/order'));

        if($orderinfo['userid'] != $_FANWE['uid']) exit;

        $anli = FDB::fetchFirst('SELECT * FROM '.FDB::table('article').' WHERE id='.$orderinfo['artid']);
        $sql = 'UPDATE '.FDB::table('user')." SET rmb=rmb+{$orderinfo['total_fee']} WHERE uid={$anli['uid']}";
        FDB::query($sql);
        $sql = 'UPDATE '.FDB::table('wogu_order')." SET flag=2 WHERE id={$orderid}";
        FDB::query($sql);
        showSuccess('提示', '确认付款成功！', FU('shareinfo/order'));
    }

    public function ordercomment() {
        global $_FANWE;

        if($_POST['id']) {
            $comment = htmlspecialchars(trim($_POST['comment']));
            if(empty($comment))
                showError('错误信息', '评论内容不能为空！', FU('shareinfo/order'));
            $orderid = intval($_POST['id']);
            $orderinfo = FDB::fetchFirst('SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$orderid);
            if(!$orderinfo) {
                showError('错误信息', '订单不存在！', FU('shareinfo/order'));
            }
            if($orderinfo['flag'] != 4)
                showError('错误信息', '订单未确认付款！', FU('shareinfo/order'));

            if($orderinfo['userid'] != $_FANWE['uid']) exit;
            $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid='.$orderinfo['shopid'];
            $shopinfo = FDB::fetchFirst($sql);
            // $starmap = array(1,2,3,4,5);
            // if(!in_array($_POST['star_pro'], $starmap) || !in_array($_POST['star_serv'], $starmap) || !in_array($_POST['star_sat'], $starmap)) {
            //     showError('错误信息', '参数错误', FU('shareinfo/order'));
            // }
            // $star_num = intval($shopinfo['star_num']) + 1;
            // $star_pro_total = intval($shopinfo['star_pro_total']) + $_POST['star_pro'];
            // $star_serv_total = intval($shopinfo['star_serv_total']) + $_POST['star_serv'];
            // $star_sat_total = intval($shopinfo['star_sat_total']) + $_POST['star_sat'];
            // $star_pro = ceil($star_pro_total / $star_num);
            // $star_serv = ceil($star_serv_total / $star_num);
            // $star_sat = ceil($star_sat_total / $star_num);
            // FDB::update('user', array(
            //     'star_num' => $star_num,
            //     'star_pro_total' => $star_pro_total,
            //     'star_serv_total' => $star_serv_total,
            //     'star_sat_total' => $star_sat_total,
            //     'star_pro' => $star_pro,
            //     'star_serv' => $star_serv,
            //     'star_sat' => $star_sat,
            // ), array('uid' => $orderinfo['shopid']));

            $grademap = array(1 => 2, 2 => 1, 3 => 0);
            $grade = in_array($_POST['grade'], $grademap) ? $_POST['grade'] : 0;
            $commentkey = empty($orderinfo['comment']) ? 'comment' : 'comment2';
            $timekey = empty($orderinfo['comment']) ? 'add_time' : 'add_time2';
            $sql = 'UPDATE '.FDB::table('wogu_order')." SET {$commentkey}='{$comment}',{$timekey}='".date('Y-m-d H:i:s')."'".($grade ? ",grade='{$grade}'" : '');
            if(!empty($_POST['pics'])) {
                $index = 1;
                foreach ($_POST['pics'] as $pic) {
                    $pic = htmlspecialchars($pic);
                    $sql .= ",`img{$index}`='{$pic}'";
                    $index++;
                }
            }
            $sql .= " WHERE id={$orderid}";
            FDB::query($sql);

            if(isset($_GET['ajax'])) {
                exit(json_encode(array(
                    'status' => 1
                )));
            } else {
                showSuccess('提示', '评论成功！', '/article.php?action=show&id='.$orderinfo['artid']);
            }
        }

        $id = intval($_GET['id']);
        $orderinfo = FDB::fetchFirst('SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$id);
        include template('page/shareinfo/shareinfo_ordercomment');
        display();
    }

    public function orderupcontract() {
        global $_FANWE;

        if($_POST['id']) {
            // if(empty($_POST['pics'])) {
            //     exit(json_encode(array(
            //         'status' => 0,
            //         'msg' => '请上传图片'
            //     )));
            // }

            $service_day = strtotime($_POST['service_day']);
            if(!$service_day) {
                exit(json_encode(array(
                    'status' => 0,
                    'msg' => '请选择时间'
                )));
            }

            if(!in_array($_POST['service_time'], array('中午', '晚上'))) {
                exit(json_encode(array(
                    'status' => 0,
                    'msg' => '请选择时间段'
                )));
            }

            $address = htmlspecialchars($_POST['address']);
            if(empty($address)) {
                exit(json_encode(array(
                    'status' => 0,
                    'msg' => '请输入婚宴地点'
                )));
            }

            $orderid = intval($_POST['id']);
            $orderinfo = FDB::fetchFirst('SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$orderid);
            if(!$orderinfo) {
                exit(json_encode(array(
                    'status' => 0,
                    'msg' => '订单不存在'
                )));
            }
            if($orderinfo['flag'] != 0) {
                exit(json_encode(array(
                    'status' => 0,
                    'msg' => '订单状态异常'
                )));
            }

            if($orderinfo['shopid'] != $_FANWE['uid']) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_order_contract').' WHERE order_id='.$orderid;
            $contract = FDB::fetchFirst($sql);
            if(!empty($contract)) {
                exit(json_encode(array(
                    'status' => 0,
                    'msg' => '订单状态异常'
                )));
            }

            $imgs = array();
            foreach ($_POST['pics'] as $pic) {
                $imgs[] = htmlspecialchars($pic);
            }
            FDB::insert('wogu_order_contract', array('order_id' => $orderid, 'imgs' => serialize($imgs), 'address' => $address));
            FDB::update('wogu_order', array('flag' => 1, 'service_day' => $_POST['service_day'], 'service_time' => $_POST['service_time']), array('id' => $orderid));
            exit(json_encode(array(
                'status' => 1
            )));
        }
    }

    public function ordersign() {
        global $_FANWE;

        if($_POST['id']) {
            $orderid = intval($_POST['id']);
            $orderinfo = FDB::fetchFirst('SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$orderid);
            if(!$orderinfo) {
                exit(json_encode(array(
                    'status' => 0,
                    'msg' => '订单不存在'
                )));
            }
            if($orderinfo['flag'] != 1) {
                exit(json_encode(array(
                    'status' => 0,
                    'msg' => '订单状态异常'
                )));
            }

            if($orderinfo['userid'] != $_FANWE['uid']) exit;
            FDB::update('wogu_order', array('flag' => 2), array('id' => $orderid));
            exit(json_encode(array(
                'status' => 1
            )));
        }
    }

    public function withdraw() {
        global $_FANWE;
        if(isset($_POST['rmb'])) {
            if(empty($_FANWE['user']['alipay']))
                showError('错误信息', '请先填写支付宝账号！', FU('settings/personal'));
            $rmb = intval($_POST['rmb']);
            if($rmb <= 0)
                showError('错误信息', '请输入正确的金额！', FU('shareinfo/withdraw'));
            $newrmb = $_FANWE['user']['rmb'] - $rmb;
            if($newrmb <= 0)
                showError('错误信息', '金额不足！', FU('shareinfo/withdraw'));

            $sql = 'UPDATE '.FDB::table('user')." SET rmb={$newrmb} WHERE uid={$_FANWE['uid']}";
            FDB::query($sql);
            FDB::insert('wogu_withdraw', array(
                'uid' => $_FANWE['uid'],
                'rmb' => $rmb,
                'dateline' => time(),
            ));

            // log
            $msg = "提现支出{$rmb}元";
            $sql = "INSERT INTO ".FDB::table('wogu_bill')." (uid,out_in,msg,dateline) VALUES('{$_FANWE['uid']}','0','{$msg}','".time()."')";
            FDB::query($sql);

            showSuccess('提示', '提现申请提交成功，我们将以站内短信形式告知处理结果，请耐心等待！', FU('shareinfo/withdraw'));
        }

        include template('page/shareinfo/shareinfo_withdraw');
        display();
    }

    public function sorder() {
        global $_FANWE;

        if($_POST['dounpay']) {
            $id = intval($_POST['id']);
            if(!$id) exit;

            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$id;
            $item = FDB::fetchFirst($sql);
            if(!$item || $item['isstop']==1) exit;
            $sql = 'UPDATE '.FDB::table('wogu_plan_items')." SET isstop='1' WHERE id='{$id}'";
            FDB::query($sql);
            $sql = 'UPDATE '.FDB::table('wogu_order')." SET isstop='1' WHERE plan_itemid='{$id}'";
            FDB::query($sql);
            $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$item['orderid'];
            $order = FDB::fetchFirst($sql);
            $money = $order['total_fee'] * ($order['paystep'] == 1 ? 0.3 : 0.8);
            $sql = 'UPDATE '.FDB::table('user').' SET rmb=rmb+'.$money.' WHERE uid='.$order['userid'];
            FDB::query($sql);
            $msg = '商家同意退款，已将订单'.($order['paystep'] == 1 ? '30%' : '80%').'的资金(共计'.$money.'元)返充到您的账户！';
            FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES({$order['userid']},'退款通知','{$msg}','".time()."')");
            FS('User')->setUserTips($order['userid'], 6);
            //log
            $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE plan_itemid='.$id;
            $orderinfo = FDB::fetchFirst($sql);
            $msg1 = "同意退款支出{$money}元[订单号:{$orderinfo['orderid']}]";
            $sql = "INSERT INTO ".FDB::table('wogu_bill')." (uid,out_in,msg,dateline) VALUES('{$_FANWE['uid']}','0','{$msg1}','".time()."')";
            FDB::query($sql);
            showSuccess('提示', '处理成功！', FU('shareinfo/sorder'));
        }

        if($_GET['op'] == 'fixprice') {
            if(!is_numeric($_GET['newp'])) exit;
            $id = intval($_GET['id']);
            if(!$id) exit;
            $sql = 'UPDATE '.FDB::table('wogu_order')." SET total_fee='{$_GET['newp']}' WHERE id='{$id}'";
            FDB::query($sql);
            exit('1');
        } elseif($_GET['op'] == 'unpay') {
            $itemid = intval($_GET['id']);
            if(!$itemid) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$itemid;
            $v = FDB::fetchFirst($sql);
            if(!$v) exit;

            $sql = 'SELECT * FROM '.FDB::table('wogu_unpay').' WHERE itemid='.$itemid;
            $unpayinfo = FDB::fetchFirst($sql);

            $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$v['orderid'];
            $orderinfo = FDB::fetchFirst($sql);

            include template('page/shareinfo/sorder_unpay');
            display();
        } else {
            $where = 'shopid='.$_FANWE['uid'];
            $sql = 'SELECT COUNT(id) FROM '.FDB::table('wogu_order').' WHERE '.$where;
            $count = FDB::resultFirst($sql);
            $page_args = array();
            $pager = buildPage('shareinfo/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);
            if($_FANWE['page'] > $pager['page'] && isset($_GET['ajax'])) {
                ajaxmsg2(0);
            }

            $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE '.$where.' ORDER BY id DESC LIMIT '.$pager['limit'];
            $res = FDB::query($sql);
            $order_list = array();
            $statuses = array('待上传合同确认', '已上传合同', '合同已签', '收到预付款', '婚礼全款已支付完成');
            while($r = FDB::fetch($res)) {
                $uids[] = $r['userid'];
                $ids[] = $r['id'];
                $r['status_show'] = $statuses[$r['flag']];
                $r['service_status'] = ($r['service_day'] != '0000-00-00' && (time() > (strtotime($r['service_day']) + 3600 * 24))) ? '服务完成' : '婚礼服务进行中';
                $r['sj'] = date('Y-m-d', $r['dateline']);
                $order_list[] = $r;
            }
            if(!empty($order_list)) {
                $uids = array_unique($uids);
                $sql = 'SELECT uid,user_name FROM '.FDB::table('user').' WHERE uid IN('.implode(',', $uids).')';
                $res = FDB::query($sql);
                while($r = FDB::fetch($res))
                    $users[$v['uid']] = $v['user_name'];

                $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE orderid IN('.implode(',', $ids).')';
                $res = FDB::query($sql);
                while($r = FDB::fetch($res)) {
                    $paysteps[$r['orderid']] = $r['paystep'];
                    $unpays[$r['orderid']] = $r['unpay'];
                    $itemids[$r['orderid']] = $r['id'];
                    $isstop[$r['orderid']] = $r['isstop'];
                }
            }

            if(isset($_GET['ajax'])) {
                ajaxmsg2(0, $order_list);
            }

            include template('page/shareinfo/shareinfo_sorder');
            display();
        }
    }

    public function createorder() {
        global $_FANWE;

        if(isset($_POST['docreate'])) {
            $artid = intval($_POST['artid']);
            if($artid <= 0) {
                ajaxmsg2(1, '参数错误');
            }
            $art = FDB::fetchFirst('SELECT * FROM '.FDB::table('article'). ' WHERE id='.$artid);
            $total_fee = floatval($_POST['price']);
            if($total_fee - $art['red_money'] <= 0) {
                ajaxmsg2(1, '总金额不能大于红包金额');
            }

            $mobile = htmlspecialchars($_POST['xn_tel']);
            $user = FDB::fetchFirst('SELECT * FROM '.FDB::table('user'). " WHERE mobile='{$mobile}'");
            if(empty($user)) {
                ajaxmsg2(1, '新娘手机号无对应的已注册账户');
            }

            $sql = 'DELETE FROM '.FDB::table('wogu_order').' WHERE artid='.$artid.' AND flag<2 AND isstop=0 AND userid='.$_FANWE['uid'];
            FDB::query($sql);
    
            $orderid = date('Ymdhis') . rand(0, 9);
            $ordername = '火锅阁案例《'.$art['title'].'》';
            $newid = FDB::insert('wogu_order', array(
                'paytype' => 3,
                'orderid' => $orderid,
                'ordername' => $ordername,
                'userid' => $user['uid'],
                'artid' => $artid,
                'shopid' => $art['uid'],
                'total_fee' => $total_fee,
                'dateline' => time(),
                'pay_mulit' => 0,
                'prepay_rate' => $art['prepay_rate'],
                'paystep' => 0,
                'red_money' => $art['red_money'],
                'service_day' => htmlspecialchars($_POST['service_day']),
                'service_time' => intval($_POST['service_time']),
                'service_day' => htmlspecialchars($_POST['service_day']),
                'flag' => 2
            ), true);
    
            if(!$newid) {
                ajaxmsg2(1, '订单创建失败');
            }
    
            FDB::insert('wogu_order_contract', array(
                'order_id' => $newid,
                'address' => htmlspecialchars($_POST['address']),
                'xl' => htmlspecialchars($_POST['xl']),
                'xl_tel' => htmlspecialchars($_POST['xl_tel']),
                'xn' => htmlspecialchars($_POST['xn']),
                'xn_tel' => htmlspecialchars($_POST['xn_tel']),
            ), true);

            ajaxmsg2(0, array(
                'orderid' => $orderid
            ));
        }

        $arts = FDB::fetchAll('SELECT * FROM '.FDB::table('article'). ' WHERE uid='.$_FANWE['uid']);
        include template('page/shareinfo/shareinfo_createorder');
        display();
    }

    public function orderdetailpc() {
        global $_FANWE;

        $order = FDB::fetchFirst('SELECT * FROM '.FDB::table('wogu_order'). ' WHERE id='.intval($_GET['id']));
        $contract = FDB::fetchFirst('SELECT * FROM '.FDB::table('wogu_order_contract'). ' WHERE order_id='.intval($_GET['id']));
        include template('page/shareinfo/shareinfo_orderdetailpc');
        display();
    }

    protected function random($length, $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ') {
        $hash = '';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

    protected function gen_file_path($dir, $extension) {
        $dir1 = date('Ym') . '/' . date('d') . '/';
        $dir2 = $dir . $dir1;
        if(!is_dir($dir2)) {
            mkdir($dir2, 0777, true);
        }

        $filename = date('His').strtolower(self::random(16)) . '.' . $extension;
        $path = $dir2 . $filename;
        return $path;
    }

    public function orderdetail() {
        global $_FANWE;

        if(isset($_GET['savesticketimg'])) {
            $id = intval($_GET['id']);
            if(!$id) {
                echo json_encode(array(
                    'error' => 'error arg'
                ));
                exit;
            }
            $uid = $_FANWE['uid'];
            $fkey = 'img';
            $whitelist = array('jpg', 'jpeg', 'png', 'gif');
            $name      = null;
            $error     = 'No file uploaded.';
            if (isset($_FILES)) {
                if (isset($_FILES[$fkey])) {
                    $extension = pathinfo($_FILES[$fkey]['name'], PATHINFO_EXTENSION);
                    $tmp_name = $_FILES[$fkey]['tmp_name'];
                    $name     = self::gen_file_path('./public/upload2/ticketimg/', $extension);
                    $error    = $_FILES[$fkey]['error'];
                    if ($error === UPLOAD_ERR_OK) {
                        if (!in_array($extension, $whitelist)) {
                            $error = 'Invalid file type uploaded.';
                        } else {
                            if(move_uploaded_file($tmp_name, $name)) {
                                FDB::update('wogu_order', array('ticket_img' => ltrim($name,'.')), 'id=' . $id);
                            }
                        }
                    }
                }
            }

            echo json_encode(array(
                'name'  => $name,
                'error' => $error
            ));
            exit;
        }

        if(!is_numeric($_GET['id'])) ajaxmsg2(1);
        $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$_GET['id'];
        $order = FDB::fetchFirst($sql);
        if(empty($order)) ajaxmsg2(1);
        $sql = 'SELECT * FROM '.FDB::table('wogu_order_contract').' WHERE order_id='.$_GET['id'];
        $contract = FDB::fetchFirst($sql);
        if(!empty($contract)) {
            $contract['imgs'] = unserialize($contract['imgs']);
        }

        $statuses = array('待上传合同确认', '已上传合同', '合同已签', '收到预付款', '婚礼全款已支付完成');
        $order['status_show2'] = $order['status_show'] = $statuses[$order['flag']];
        if($order['flag'] < 3) {
            $order['service_status'] = '等待用户确认合同，支付定金';
        } else {
            $order['service_status'] = (time() > (strtotime($order['service_day']) + 3600 * 24)) ? '服务完成' : '婚礼服务进行中';
        }
        $order['sj'] = date('Y-m-d', $order['dateline']);
        if($order['flag'] == 3) {
            $thatday = date('Y-m-d', strtotime($order['service_day']) - 7 * 3600 * 24);
            $money = $order['total_fee'] * 0.7;
            $order['status_show2'] = "定金30%已付，婚礼日前一周支付尾款70%。即{$thatday}支付尾款70%（{$money}元）";
        }
        ajaxmsg2(0, array(
            'order' => $order,
            'contract' => $contract,
        ));
    }

    public function wu() {
        global $_FANWE;

        $config = include FANWE_ROOT . 'public/plan.php';

        if($_POST['docomp']) {
            $id = intval($_POST['id']);
            if(!$id) exit;
            $itemid = intval($_POST['itemid']);
            $tipid = intval($_POST['tipid']);
            if($tipid < 0) exit;

            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$id;
            $v = FDB::fetchFirst($sql);
            if(!$v) exit;
            $item = $v['pid'] == -1 ? $config[$v['myid']] : $config[$v['pid']]['children'][$v['myid']];
            $data = empty($v['data']) ? array() : unserialize($v['data']);
            $data[$itemid] = array(
                'dateline' => time(),
                'tipid' => $tipid,
                'tip' => htmlspecialchars(trim($_POST['tip']))
            );
            $flag = count($data) == count($item['items']) ? 1 : 0;
            if(FDB::update('wogu_plan_items', array('data' => serialize($data), 'flag' => $flag), array('id' => $id)))
                exit('1');
            exit;
        }

        if($_GET['op'] == 'show') {
            $itemid = intval($_GET['id']);
            if(!$itemid) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$itemid;
            $v = FDB::fetchFirst($sql);
            if(!$v) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_list').' WHERE id='.$v['list_id'];
            $plan = FDB::fetchFirst($sql);
            $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid='.$plan['uid'];
            $user = FDB::fetchFirst($sql);

            $item = $v['pid'] == -1 ? $config[$v['myid']] : $config[$v['pid']]['children'][$v['myid']];
            $item['item_id'] = $v['id'];
            $item['data'] = empty($v['data']) ? array() : unserialize($v['data']);
            $item['flag'] = $v['flag'];
            $item['shopid'] = $v['shopid'];
            $item['isstop'] = $v['isstop'];
            $item['unpay'] = $v['unpay'];
            include template('page/shareinfo/shareinfo_wu_show');
        } else {
            $where = 'pi.shopid='.$_FANWE['uid'];
            $sql = 'SELECT COUNT(pi.id) FROM '.FDB::table('wogu_plan_items').' pi WHERE '.$where;
            $count = FDB::resultFirst($sql);
            $page_args = array();
            $pager = buildPage('list/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);

            $sql = 'SELECT pi.*,pl.tip,pl.dateline as sj FROM '.FDB::table('wogu_plan_items').' pi LEFT JOIN '.FDB::table('wogu_plan_list').' pl ON pi.list_id=pl.id WHERE '.$where.' ORDER BY pi.id DESC LIMIT '.$pager['limit'];
            $rs = FDB::query($sql);
            $uids = array();
            while($r = FDB::fetch($rs)) {
                $wu_list[] = $r;
                $uids[] = $r['uid'];
            }
            if(!empty($uids)) {
                $uids = array_unique($uids);
                $sql = 'SELECT uid,user_name FROM '.FDB::table('user').' WHERE uid IN('.implode(',', $uids).')';
                $rs = FDB::query($sql);
                while($r = FDB::fetch($rs))
                    $users[$r['uid']] = $r['user_name'];
            }
            include template('page/shareinfo/shareinfo_wu');
        }
        display();
    }

    public function bill() {
        global $_FANWE;

        $where = 'uid='.$_FANWE['uid'];
        $sql = 'SELECT COUNT(id) FROM '.FDB::table('wogu_bill').' WHERE '.$where;
        $count = FDB::resultFirst($sql);
        $page_args = array();
        $pager = buildPage('shareinfo/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);
        $sql = 'SELECT * FROM '.FDB::table('wogu_bill').' WHERE '.$where.' ORDER BY id DESC LIMIT '.$pager['limit'];
        $bill_list = FDB::fetchAll($sql);
        include template('page/shareinfo/shareinfo_bill');
        display();
    }
}

function random2($length, $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ') {
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

$formatTree; //用于树型数组完成递归格式的全局变量

function toTree($list=null, $pk='id',$pid = 'parent_id',$child = '_child') {
    global $formatTree;

    if(null === $list)
		return;

    // 创建Tree
    $tree = array();
    if(is_array($list))
	{
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $_key = is_object($data)?$data->$pk:$data[$pk];
            $refer[$_key] =& $list[$key];
        }

        foreach ($list as $key => $data)
		{
            // 判断是否存在parent
            $parentId = is_object($data)?$data->$pid:$data[$pid];
            $is_exist_pid = false;
            foreach($refer as $k=>$v)
            {
            	if($parentId==$k)
            	{
            		$is_exist_pid = true;
            		break;
            	}
            }

            if ($is_exist_pid)
			{
                if (isset($refer[$parentId]))
				{
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
			else
			{
                $tree[] =& $list[$key];
            }
        }
    }

    return $tree;
}

function _toFormatTree($list,$level=0,$dispname_arr=array('title'))
{
    global $formatTree;

	  foreach($list as $key=>$val)
	  {
		$tmp_str=str_repeat("&nbsp;&nbsp;",$level*2);
		$tmp_str.="|--";
		foreach($dispname_arr as $dispname)
		{
			$val[$dispname]=$tmp_str."&nbsp;&nbsp;".$val[$dispname];
		}

		$val['level'] = $level;
		if(!array_key_exists('_child',$val))
		{
		   array_push($formatTree,$val);
		}
		else
		{
		   $tmp_ary = $val['_child'];
		   unset($val['_child']);
		   array_push($formatTree,$val);
		   _toFormatTree($tmp_ary,$level+1,$dispname_arr); //进行下一层递归
		}
	  }

	  return;
}

function toFormatTree($list,$dispname_arr=array('title'),$pk='id',$pid = 'parent_id')
{
    global $formatTree;

	if(!is_array($dispname_arr))
		$dispname_arr = array($dispname_arr);

    $formatTree = array();
	$list = toTree($list,$pk,$pid);
	_toFormatTree($list,0,$dispname_arr);
	return $formatTree;
}

function isTel($tel,$type='') {
  $regxArr = array(
  'tel' =>  '/^(010|02\d{1}|0[3-9]\d{2})-\d{7,9}(-\d+)?$/',
  '400' =>  '/^400(-\d{3,4}){2}$/',
  );
  if($type && isset($regxArr[$type]))
  {
    return preg_match($regxArr[$type], $tel) ? true:false;
  }
  foreach($regxArr as $regx)
  {
    if(preg_match($regx, $tel ))
    {
      return true;
    }
  }
  return false;
}